package lucene.server.client;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.stream.Collectors;

public class QueryClient {
    private String path="/client/wrapper";
    private String url;
    private String app;
    private String secret;

    public QueryClient(String url,String app,String secret) {
        this.app = app;
        this.secret = secret;
        this.url = url + this.path;
    }
    public String request(ClientWrapper wrapper) {
        return doPost(this.url, wrapper.build());
    }


    /**
     * POST请求
     *
     * @param url
     * @param jsonData
     * @return
     */
    public  String doPost(String url,String  jsonData) {
        OutputStream outputStream = null;
        BufferedReader reader = null;
        String errorMsg = "";
        try {
            //建立连接
            URL queryUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);   //允许写入输出流
            connection.setUseCaches(false); //禁用缓存
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            //创建头部鉴权
            createHeaders(connection);

            // 写入请求体
            outputStream = connection.getOutputStream();
            outputStream.write(jsonData.getBytes(StandardCharsets.UTF_8)); // 写入JSON数据
            outputStream.flush();
            outputStream.close();

            //发送请求
            InputStream inputStream ;
            if(connection.getResponseCode()==200){
                //发送请求
                inputStream = connection.getInputStream();

            }else {
                inputStream = connection.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String response = reader.lines().collect(Collectors.joining(System.lineSeparator()));
            inputStream.close();
            reader.close();
            return response;

        } catch (Exception e) {
            errorMsg = e.getMessage();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    errorMsg = e.getMessage();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    errorMsg = e.getMessage();
                }
            }
        }
        return "{\"success\":false,\"message\":\""+errorMsg+"\",\"code\":500,\"result\":null,\"timestamp\":0}";
    }

    private void  createHeaders(HttpURLConnection connection) {
        long timestamp  = System.currentTimeMillis();
        String sign = generateMD5(this.app+this.secret+timestamp);
        connection.setRequestProperty("timestamp", String.valueOf(timestamp));
        connection.setRequestProperty("app", this.app);
        connection.setRequestProperty("sign",sign);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    }
    /**
     * 生成一个32位的MD5哈希值（十六进制字符串形式）
     * @param input 输入字符串
     * @return MD5哈希值的十六进制字符串
     */
    public static String generateMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

}